#include "common_lib/topo_map.h"

using namespace CommonLib;

PointAttr::PointAttr(Json::Value value)
{
    pointid = value["id"].asString();
    x = value["pos_x"].asFloat() * 0.001f;
    y = value["pos_y"].asFloat() * 0.001f;
    z = value["pos_z"].asFloat() * 0.001f;
}

PathAttr::PathAttr(Json::Value value)
{
    pathid = value["id"].asString();
    start  = value["node_1"].asString();
    end    = value["node_2"].asString();
    controlpoints.push_back(start);
    controlpoints.push_back(end);
    keypoints = controlpoints;
    direction = "start2end";
    amr_angle = value["amr_angle"].asFloat();
    angle_type = value["angle_type"].asString();
    maxspeed = value["max_speed"].asFloat()*0.001f;
    pathtype = "line"; // TODO
}

bool TopoGraph::LoadPoints(Json::Value &value)
{
    if (value["nodes"].isNull())
    {
        return false;
    }
    for (int i=0;i<value["nodes"].size();i++)
    {
        std::shared_ptr<PointAttr> p(new PointAttr(value["nodes"][i]));
        ptr_point[value["nodes"][i]["id"].asString()] = p;
    }
    return true;
}

bool TopoGraph::LoadPaths(Json::Value &value)
{
    if (value["edges"].isNull())
    {
        return false;
    }
    for (int i=0;i<value["edges"].size();i++)
    {
        std::shared_ptr<PathAttr> p(new PathAttr(value["edges"][i]));
        ptr_path[value["edges"][i]["id"].asString()] = p;
    }
    return true;
}

bool TopoGraph::LoadGraph(std::string mapfile)
{
    Json::Reader reader;
    Json::Value root;
    std::ifstream in(mapfile, std::ios::binary);
    if (!reader.parse(in, root))
    {
        return false;
    }
    timestamp = root["timestamp"].asString();
    if (!LoadPoints(root))
    {
        return false;
    }
    if (!LoadPaths(root))
    {
        return false;
    }
    in.close();
    return true;
}